﻿using Games.Common;
using Games.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Games.DigitalSame
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    partial class GamePage : ContentPage
    {
        IDataBase database = DependencyService.Get<IDataBase>();
        private Game game;
        private readonly GameInfo gameInfo;
        private LightGameArg lightGameArgs;
        const int CellSpacing = 2;
        ScrollView view;
        IDictionary<string, Button> buttons;
        int cellSize;
        int layoutWidth, layoutHeight;
        internal GamePage(GameInfo gamePage)
        {
            InitializeComponent();
            BindingContext = gameInfo = gamePage;
            game = new Game();
            LoadAsync().Wait();
            database.CreateTable<DigitalSameRecord>();
        }
        async Task LoadAsync()
        {
            var gameArgs = await database.GetFirstOrDefaultAsync<GameArgs>(x => x.GameID == gameInfo.ID).ConfigureAwait(false);
            if(gameArgs != null)
            {
                lightGameArgs = BaseArgs.Convert<LightGameArg>(gameArgs);
                gameInfo.Width = lightGameArgs.Width;
                gameInfo.Height = lightGameArgs.Height;
            }
            else
            {
                gameInfo.Width = gameInfo.Height = 3;
                lightGameArgs = new LightGameArg
                {
                    Width = gameInfo.Width,
                    Height = gameInfo.Height,
                    GameID = gameInfo.ID,
                    //Version = gameInfo.Version,
                };
            }
        }
        async Task SaveArgsAsync()
        {
            lightGameArgs.Width = gameInfo.Width;
            lightGameArgs.Height = gameInfo.Height;
            await database.SaveAsync(lightGameArgs.ToGameArgs());
        }
        void OnLayoutSizeChanged(object sender, EventArgs args)
        {
            Layout layout = sender as Layout;
            layoutWidth = (int)layout.Width;
            layoutHeight = (int)layout.Height;
            InitLayout();
        }

        void InitLayout(bool isReload = false)
        {
            if(!isReload || game.IsFinished)
            {
                game.Init(gameInfo.Width, gameInfo.Height);
            }
            else
            {
                game.Reload();
            }
            gameInfo.ClickCount = 0;

            var sizew = (layoutWidth - CellSpacing * 2) / gameInfo.Width;
            var sizeh = (layoutHeight - CellSpacing * 2) / gameInfo.Height;
            cellSize = Math.Min(sizew, sizeh);
            var layWidth = gameInfo.Width * cellSize + CellSpacing;
            var layHeight = gameInfo.Height * cellSize + CellSpacing;
            absoluteLayout.WidthRequest = layWidth;
            absoluteLayout.HeightRequest = layHeight;
            var xMargin = (layoutWidth - layWidth) / 2.0;
            var yMargin = (layoutHeight - layHeight) / 2.0;
            absoluteLayout.Margin = new Thickness(xMargin, yMargin);
            var count = gameInfo.Width * gameInfo.Height;

            while(absoluteLayout.Children.Count > count)
            {
                absoluteLayout.Children.RemoveAt(0);
            }


            while(absoluteLayout.Children.Count < count)
            {
                GameCell lifeCell = new GameCell();
                lifeCell.Tapped += OnTapGestureTapped;
                absoluteLayout.Children.Add(lifeCell);
            }

            for(int x = 0; x < gameInfo.Width; x++)
            {
                for(int y = 0; y < gameInfo.Height; y++)
                {
                    var index = x * gameInfo.Height + y;
                    GameCell lifeCell = (GameCell)absoluteLayout.Children[index];
                    lifeCell.Col = x;
                    lifeCell.Row = y;
                    lifeCell.FontSize = cellSize / 2;
                    lifeCell.InitValue(game.GetValue(x, y), game.GetClick(x, y));
                    Rectangle rect = new Rectangle(x * cellSize + CellSpacing,
                                                   y * cellSize + CellSpacing,
                                                   cellSize - CellSpacing,
                                                   cellSize - CellSpacing);

                    AbsoluteLayout.SetLayoutBounds(lifeCell, rect);
                    lifeCell.Show();
                }
            }
            TimeCounter.Start();
        }
        async void OnTapGestureTapped(object sender, EventArgs args)
        {
            if(game.IsFinished)
            {
                return;
            }
            GameCell lifeCell = (GameCell)sender;
            game.Click(lifeCell.Col, lifeCell.Row);
            await lifeCell.ScaleBack(0.95);
            lifeCell.Grow(true);

            TryChange(lifeCell.Col + 1, lifeCell.Row);
            TryChange(lifeCell.Col - 1, lifeCell.Row);
            TryChange(lifeCell.Col, lifeCell.Row + 1);
            TryChange(lifeCell.Col, lifeCell.Row - 1);
            gameInfo.ClickCount++;
            if(game.IsFinished)
            {
                await ShowFinish();
            }
        }

        void TryChange(int x, int y)
        {
            if(game.InBoard(x, y))
            {
                var index = x * gameInfo.Height + y;
                GameCell lifeCell = (GameCell)absoluteLayout.Children[index];
                lifeCell.Grow();
            }
        }
        async Task ShowFinish()
        {
            var record = await SaveRecordAsync();
            await DisplayAlert(record.Level, record.Message, "OK");
        }
        async Task<Record> SaveRecordAsync()
        {
            var dur = TimeCounter.Stop();
            var click = gameInfo.ClickCount;
            var cRecord = new DigitalSameRecord()
            {
                Width = gameInfo.Width,
                Height = gameInfo.Height,
                GameID = gameInfo.ID,
                ClickCount = game.ClickCount,
                AllClickCount = game.AllClickCount,
                CreateTime = DateTime.Now,
                Duration = dur,
                Score = game.ClickCount * 1.0 / game.AllClickCount
            };
            await database.SaveRecordByLevel(cRecord,
                o => o.Width == cRecord.Width && o.Height == cRecord.Height && o.ClickCount == cRecord.ClickCount,
                o => o.AllClickCount > cRecord.AllClickCount || (o.AllClickCount == cRecord.AllClickCount && o.Duration > cRecord.Duration)
            );
            return cRecord.Convert();
        }

        async void LevelClicked(object sender, EventArgs args)
        {
            if(!mask.Contains("levels"))
            {
                var diffs = Enumerable.Range(3, 5).Select(x => $"{x} * {x}").ToList();
                (view, buttons) = ControlUtil.GetLevelGrid(diffs, -1, 1, LevelSelect);
                mask.SetSize("levels", 0.8, 0.64);
                mask.Add("levels", "选择难度", view);
            }
            mask.ShowWithCancel("levels");
            var str = $"{gameInfo.Width} * {gameInfo.Height}";
            await view.ScrollToAsync(this.buttons[str], ScrollToPosition.Center, false);
        }
        async void LevelSelect(string str)
        {
            mask.Hide();
            var level = str[0] - '0';
            if(gameInfo.Width != level)
            {
                gameInfo.Height = gameInfo.Width = level;
                await SaveArgsAsync();
            }
            InitLayout();
        }

        void RestartClicked(object sender, EventArgs args)
        {
            InitLayout(true);
        }

        void OnAboutButtonClicked(object sender, EventArgs args)
        {
            if(!mask.Contains("about"))
            {
                var aboutView = ControlUtil.GetAbout(gameInfo);
                mask.Add("about", gameInfo.Name, aboutView);
            }
            mask.ShowWithCancel("about", "确定");
        }
        void OnRecordClicked(object sender, EventArgs args)
        {
            //var sorter = new Sorter<DigitalSameRecord>(q => q.OrderByDescending(x => x.Width).ThenBy(x => x.Score).ThenBy(x => x.Duration).ThenByDescending(x => x.ID));
            Navigation.PushAsync(new RecordPage(gameInfo.Name, new RecordViewModel<DigitalSameRecord>(null)));
        }

        private void TapToBack(object sender, EventArgs e)
        {
            Navigation.PopAsync();
        }
    }
}